﻿#include<iostream>
#include<asio.hpp>
using namespace std;
using asio::ip::tcp;

std::string make_daytime_string()
{
	auto t = std::time(nullptr);
	return std::ctime(&t);
}

class tcp_connection : public std::enable_shared_from_this<tcp_connection>
{
public:
	using pointer = std::shared_ptr<tcp_connection>;

	static pointer create(asio::io_service& io_service)
	{
		return std::shared_ptr<tcp_connection>(new tcp_connection(io_service));
		//return std::make_shared<tcp_connection>(io_service);
	}
	void handle_write()
	{
		std::cout << endpoint_.address().to_string() << " " << endpoint_.port() << std::endl;
		socket_.write_some(asio::buffer(message_));
	}
	tcp::socket& socket() { return socket_; }
	tcp::endpoint& endpoint() { return endpoint_; }
private:
	tcp_connection(asio::io_service& io_service)
		:socket_(io_service)
	{
		message_ = make_daytime_string();
	}
	tcp::socket socket_;
	std::string message_;
	tcp::endpoint endpoint_;
};


void start_accept(tcp::acceptor& acceptor,asio::io_service& io_service)
{
	tcp_connection::pointer new_connection = tcp_connection::create(io_service);
	acceptor.async_accept(new_connection->socket(),new_connection->endpoint(), [&acceptor, new_connection, &io_service](const std::error_code& err)
		{
			std::cout << "have new connection" << std::endl;
			if (!err)
				start_accept(acceptor,io_service);
			new_connection->handle_write();
		});
}

int main()
{
	try
	{
		//创建服务
		asio::io_service io_service;
		//创建接受器
		tcp::acceptor acceptor(io_service,tcp::endpoint(asio::ip::address_v4::any(),13));
		
		//new_socket.write_some(asio::buffer(string()));

		start_accept(acceptor, io_service);


		//while (true)
		//{
		//	auto new_socket = acceptor.accept();
		//	new_socket.write_some(asio::buffer(make_daytime_string()));
		//}

		//运行服务
		io_service.run();
	}
	catch (const std::exception& e)
	{
		std::cout << "has exception " << e.what() << std::endl;
	}


	return 0;
}
//服务器方向 asio